package push

import (
	"errors"

	"gitee.com/gao-deguang/easy-chat/apps/im/ws/internal/svc"
	"gitee.com/gao-deguang/easy-chat/apps/im/ws/websocket"
	"gitee.com/gao-deguang/easy-chat/apps/im/ws/ws"
	"gitee.com/gao-deguang/easy-chat/pkg/constant"
	"github.com/mitchellh/mapstructure"
	"github.com/zeromicro/go-zero/core/logx"
)

func Push(svc *svc.ServiceContext) websocket.HandleFunc {
	return func(srv *websocket.Server, conn *websocket.Conn, msg *websocket.Message) {
		var data ws.Push
		logx.Info("看看msg看看msg看看msg看看msg看看msg看看msg:", msg)
		if err := mapstructure.Decode(msg.Data, &data); err != nil {
			srv.Send(websocket.NewErrMessage(err))
			return
		}
		logx.Info("看看Data看看Data看看Data看看Data看看Data:", data)
		switch data.ChatType {
		case constant.SingleChat:
			single(srv, &data, data.RecvId)
		case constant.GroupChat:
			groupChat(srv, &data, data.RecvIds)
		}
	}
}

func single(svr *websocket.Server, data *ws.Push, recvId string) error {
	rconn := svr.GetConn(recvId)
	users := svr.GetUsers()
	logx.Info("看看users看看users看看users看看users:%v", users)
	if rconn == nil {
		//todo:目标离线
		logx.Info("rconn为空rconn为空rconn为空rconn为空rconn为空rconn为空rconn为空")
		return errors.New("用户离线,rconn为空")
	}

	svr.Infof("push msg :%v", data)
	svr.Send(websocket.NewMessage(data.SendId, &ws.Chat{
		ConversationId: data.ConversationId,
		ChatType:       data.ChatType,
		SendId:         data.SendId,
		RecvId:         data.RecvId,
		SendTime:       data.SendTime,
		Msg: ws.Msg{
			MsgId:   data.MsgId,
			Mtype:   data.Mtype,
			Content: data.Content,
		},
	}), rconn)

	return nil
}

func groupChat(svr *websocket.Server, data *ws.Push, recvIds []string) error {
	for _, id := range recvIds {
		func(id string) {
			svr.Schedule(func() {
				single(svr, data, id)
			})
		}(id)
	}
	return nil
}
